<template>
  <div>
    <Form :label-width="100" ref="dataToQuery" :model="dataToQuery">
      <Row :gutter="16" class="query-form">
        <i-col span="8">
          <FormItem label="审计标准名称：" prop="auditName">
            <Input v-model="dataToQuery.auditName"/>
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="板块：" prop="auditPlate">
            <Input v-model="dataToQuery.auditPlate"/>
          </FormItem>
        </i-col>
        <i-col span="8">
          <div style="float: right">
            <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
            <Button class="ivu-btn-query" icon="md-search"  @click="dataToquery">查询</Button>
          </div>
        </i-col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" type="success" class="ivu-btn-add" icon="md-add"
                  v-if="this.user.loginId === this.Common.admin || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7' || obj.roleId == '6a57d3bde6544c4495ceace17399fd26') != undefined"
                  @click="addInfo">新增
          </Button>
          <Button size="large" type="success" class="ivu-btn-add" icon="md-add"
                  v-if="this.user.loginId === this.Common.admin || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7' || obj.roleId == '6a57d3bde6544c4495ceace17399fd26') != undefined"
                  @click="addModInfo">基于现有标准新增
          </Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :loading="loading" border :columns="columns" no-data-text="请选择二级集团"
           :data="dataTable" width="100%" :height="tableHeight"  highlight-row stripe size="small"
           @on-selection-change="selectData"
    ></Table>
    <Row type="flex" justify="end" >
      <i-col>
        <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
              @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
      </i-col>
    </Row>
    <Modal :title="add?'审计'+name+'标准新增':'审计'+name+'标准修改'" :transfer=false v-model="model1" :width=900>
      <Row>
        <Col span="24">
          <Form ref="dataToView" :model="dataToView" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem :label="orgName+'：'" prop="twoLevelGroupName">
                  <Input v-model="dataToView.twoLevelGroupName" :readonly="true"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="年份：" prop="auditYear">
                  <DatePicker type="year" :value="dataToView.auditYear" placeholder="请选择"
                              style="width: 100%"></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="审计标准名称：" prop="auditName">
                  <Input v-model="dataToView.auditName"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="板块：" >
                  <Input v-model="dataToView.auditPlate"/>
                </FormItem>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：" prop="userName">
                  <Input v-model="dataToView.userName" :readonly="true"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报时间:" prop="createDate">
                  <Input v-model="dataToView.createDate" :readonly="true"/>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button  class='ivu-btn-save' :loading="buttonLoading"
                @click="submit('dataToView')">确定
        </Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal :title="'审计'+name+'标准新增'" :transfer=false v-model="model3" :width=900>
      <Row>
        <Col span="24">
          <Form ref="saveAll" :model="dataToView" :rules="ruleCustomAll" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem :label="orgName+'：'" prop="twoLevelGroupName">
                  <Input v-model="dataToView.twoLevelGroupName" :readonly="true"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="年份：" prop="auditYear">
                  <DatePicker type="year" :value="dataToView.auditYear" placeholder="请选择"
                              style="width: 100%"></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="审计标准名称：" prop="auditName">
                  <Input v-model="dataToView.auditName"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="板块：" >
                  <Input v-model="dataToView.auditPlate"/>
                </FormItem>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：" prop="userName">
                  <Input v-model="dataToView.userName" :readonly="true"/>
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报时间:" prop="createDate">
                  <Input v-model="dataToView.createDate" :readonly="true"/>
                </FormItem>
              </Col>
            </Row>
            <div style="height: 330px; overflow-y: auto; overflow-x: auto;">
              <Tree ref="auditTree"   show-checkbox multiple :data="orderTreeHead"></Tree>
            </div>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button  class='ivu-btn-save' :loading="buttonLoading"
                @click="saveAll('dataToView')">确定
        </Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal title="审计现场标准详情" :transfer=false v-model="model2" :width=800 class="modal-view-detail">
      <Row>
        <Col span="24">
          <Form :model="dataToView" :label-width="160">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="所属二级集团：" prop="stdOrgName">
                  {{dataToView.twoLevelGroupName}}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="审计标准名称:" >
                  {{dataToView.auditName}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="板块:" >
                  {{dataToView.auditPlate}}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="年份：" prop="auditYear">
                  {{ dataToView.auditYear }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="总分:">
                  {{ dataToView.score }}
                </FormItem>
              </Col>

            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="填报人：" >
                  {{dataToView.userName}}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="填报时间：" >
                  {{formatDate(new Date(dataToView.createDate),'yyyy-MM-dd')}}
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {sessionStorage} from "@/common/cacheUtils";
import {Api} from "@/api";

export default {
name: "StandardsTable",
  props:['type','orgName'],
  data(){
    return{
      model3:false,
      add:false,
      loading:false,
      buttonLoading:false,
      tableHeight:null,
      model1:false,
      model2:false,
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      twoLevelOrgId:null,
      twoLevelOrgName:null,
      dataTable:[],
      dataToView:{},
      pageSizeArray: [10, 20, 50],
      dataToQuery:{},
      orderTreeHead:[
        {
          id:1,
          loading: false,
          title: '安全审计标准',
          expand: false,
          children: []
        }
      ],
      columns:[
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left',
        },
        {
          title: "序号",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '审计名称',
          minWidth: 150,
          align: 'center',
          key: 'auditName',
        },
        {
          title: '年份',
          minWidth: 150,
          align: 'center',
          key: 'auditYear',
        },
        {
          title: '板块',
          minWidth: 150,
          align: 'center',
          key: 'auditPlate',
        },
        {
          title: '所属二级集团',
          minWidth: 200,
          align: 'center',
          key: 'twoLevelGroupName',
        },
        {
          title: '总分',
          minWidth: 150,
          align: 'center',
          key: 'score',
        },
        {
          title: '填报人',
          minWidth: 150,
          align: 'center',
          key: 'userName',
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          minWidth: 160,
          fixed: 'right',
          render: (h, params) => {
            if (this.user.loginId === this.Common.admin
                || this.user.userId === params.row.createUserId
                || this.user.userRole.find(obj => obj.roleId == 'dda573b123f9472d95ba3063b25133f7') != undefined
                || this.user.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',

                  },
                  on: {
                    click: () => {
                      this.showData(params, 2);
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: 'red'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: '<p>是否要删除？</p>',
                        onOk: () => {
                          this.deleteData(params);
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, '删除')
              ]);
            }else{
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }

          }
        },

      ],
      ruleCustom:{

        twoLevelGroupName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditYear: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditPlate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        userName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        createDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      ruleCustomAll:{
        twoLevelGroupName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditYear: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        auditPlate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        userName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        createDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      user:sessionStorage('userId').getObject('userId'),
      saveUrl:Api.saveAuditStandards,
      updateUrl:Api.updateAuditStandards,
      queryUrl:Api.queryAuditStandards,
      deleteUrl:Api.deleteAuditStandards,
      name:"",
      selectDataList:[],

    }
  },
  mounted(){
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
  },
  methods:{
    showData(data, flag) {
      this.dataToView =  JSON.parse(JSON.stringify(data.row));
      if (flag == 1) {
        //查看页面
        this.model2 = true;
      } else {
        this.$set(this.dataToView,'createDate',this.formatDate(new Date(this.dataToView.createDate),'yyyy-MM-dd'))
        this.buttonLoading = false;
        this.add = false;
        this.model1 = true;
      }
    },
    addModInfo(){
      if (this.selectDataList.length > 1){
        this.$Message.warning("只能选择一条数据")
      }else if (this.selectDataList.length == 0){
        this.$Message.warning("请选择一条数据")
      }else{
        this.orderTreeHead = [
          {
            id:1,
            loading: false,
            title: '安全审计标准',
            expand: false,
            children: []
          }
        ];
        this.dataToView = {
          userName: this.user.userName,
          createDate: this.formatDate(new Date(), 'yyyy-MM-dd'),
          twoLevelGroupName: this.twoLevelOrgName,
          twoLevelGroupId: this.twoLevelOrgId,
          auditYear: this.formatDate(new Date(), 'yyyy'),
          standardsId:this.selectDataList[0],

        };
        this.auditTree()
        this.model3 = true;

      }
    },
    auditTree(){
      let _this = this;
      _this.orderTreeHead = [{
        id:1,
        loading: true,
        title: '安全审计标准',
        expand: false,
        children:[],
      }]
      if(this.dataToView.standardsId){
       // this.dataToView.auditYear = this.formatDate(this.dataToView.auditYear, 'yyyy')
        this.buttonLoading = true;
        this.$http.get(Api.queryAuditStandardsTreeList, {
          params: {standardId:this.dataToView.standardsId}
        }).then(function(res){
          if(res.data.status == '200'){
            _this.orderTreeHead =
                [
                  {
                    id:1,
                    loading: false,
                    title: '安全审计标准',
                    expand: true,
                    children: res.data.data
                  }
                ]
          }
          this.buttonLoading = false;
        }, function(res){
          this.$Message.error('请求失败');
        });
      }else{
        _this.orderTreeHead = [{
          id:1,
          loading: false,
          title: '安全审计标准',
          expand: false,
          children:[],
        }]
      }

    },
    setTwoLevelOrgId(orgId,orgName){
      if (this.type == '1'){
        this.name = "基础"
      }else if (this.type == '2'){
        this.name = "现场"
      }else{
        this.name = "班组"
      }
      this.twoLevelOrgId = orgId;
      this.twoLevelOrgName = orgName;
      this.query();
    },
    pageSizeChange(pageSize){
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    pageChange(pageNum){
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    cancel() {
      this.dataToQuery = {};
      this.query();
    },
    selectData(select){
      this.selectDataList = [];
      select.forEach(item => {
        this.selectDataList.push(item.id)
      });
    },
    query(){
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,

      };
      this.selectDataList = [];
      this.$set(this.dataToQuery,'twoLevelGroupId',this.twoLevelOrgId)
      this.$set(this.dataToQuery,'auditType',this.type);
      // Vue.set(this.dataToQuery,'twoLevelGroupId',this.id)
      data = Object.assign(data, JSON.parse(JSON.stringify(this.dataToQuery)));
      this.$http.get(this.queryUrl, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败");
        this.loading = false;
      })
    },
    dataToquery(){
      this.pagedata.currentPage = 1;
      this.query();
    },
    addInfo(){
      this.dataToView = {
        userName: this.user.userName,
        createDate: this.formatDate(new Date(), 'yyyy-MM-dd'),
        twoLevelGroupName: this.twoLevelOrgName,
        twoLevelGroupId: this.twoLevelOrgId,
        auditYear: this.formatDate(new Date(), 'yyyy'),

      };
      this.add = true;
      this.model1 = true;

    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
    saveAll(name){
      let _this = this;
      this.$refs[name].validate((valid) => {
        if(valid){
          let tree = this.$refs.auditTree.getCheckedNodes();
          if (tree.length){
            _this.buttonLoading = true;
            _this.dataToView.nodes = tree;
            _this.dataToView.auditType = this.type;
            _this.$http.post(Api.saveAllStandards,_this.dataToView).then((res)=>{
                if (res.data.status == '200'){
                  _this.model3 = false;
                  this.$emit('update','1');
                  this.query()
                  _this.$Message.success("保存成功")
                }else{
                  _this.$Message.error(res.data.msg);
                }
              _this.buttonLoading = false;
            }).catch(e => {
              _this.buttonLoading = false;
              this.$Message.error({
                content: '保存失败',
                duration: 4
              });
            })
          }else{
            _this.$Message.error("至少选择一条标准")
          }
        }else{
          _this.$Message.error("请填报完整")
        }
      })
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          let userId = this.user.userId;
          let orgId = this.user.orgInfo.orgId;
          this.dataToView.auditType = this.type;
          //this.dataToView.auditYear = this.formatDate(this.dataToView.auditYear, 'yyyy')
          if (this.add) {
            this.dataToView.createUsrId = userId;
            this.dataToView.createOrgId = orgId;
            this.$http.post(this.saveUrl, this.dataToView).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.saveMod = false;
                this.$emit('update','1');
                this.query()
              }else{
                this.$Message.error(res.data.msg);
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("新增失败")
            })
          } else {
            this.dataToView.updateUserId = userId;
            this.dataToView.updateOrgId = orgId;
            this.$http.put(this.updateUrl, this.dataToView).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.$emit('update','1');
                this.query()

              } else{
                this.$Message.error(res.data.msg);
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("修改失败")
            })
          }



        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    handleCancel(){
      this.model1 = false;
      this.model3 = false;
      this.dataToView = {};
    },
    deleteData(params) {
      this.$http.delete(this.deleteUrl + '/' + params.row.id, {params: {}}).then((res) => {
        if (res.data.status === 200) {
          this.$emit('update','1');
          this.$Message.success('成功');
          this.query()
        } else{
          this.$Message.error(res.data.msg);
        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
  }

}
</script>

<style scoped>

</style>
